<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <?php
    $dbh = new PDO('mysql:host=172.17.0.1;dbname=ducheng', 'root', '123456');
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $dbh->exec('set names utf8');
    //全局数据
    $error = '';
    $success = '';
    $data = [];
    $nowDate = date('Y-m-d');
    $nowDateTime = date('Y-m-d H:i:s');
    //查询是否锁定
    $sql = "SELECT * FROM `order_lock` WHERE `lock_time` = :lock_time";
    $stmt = $dbh->prepare($sql);
    $stmt->execute([':lock_time' => $nowDate]);
    $lockRow = $stmt->fetch(PDO::FETCH_ASSOC);
    if (empty($lockRow)) {
        $isLock = false;
    } else {
        $isLock = true;
    }
    if (!empty($_POST)) {
        $type = isset($_POST['type']) ? trim($_POST['type']) : '';
        switch ($type) {
            case 'suborder'://提交订单
                try {
                    if ($isLock) {
                        throw new \Exception('系统已经锁定，不能提交订单了。');
                    }
                    $data['user_name'] = isset($_POST['user_name']) ? trim($_POST['user_name']) : '';
                    if (empty($data['user_name'])) {
                        throw new \Exception('请填写您的姓名');
                    }
                    $data['goods_name'] = isset($_POST['goods_name']) ? trim($_POST['goods_name']) : '';
                    if (empty($data['goods_name'])) {
                        throw new \Exception('请输入您要点的菜名');
                    }
                    $data['price'] = isset($_POST['price']) ? (float)$_POST['price'] : 0;
                    if ($data['price'] <= 0) {
                        throw new \Exception('请填写有效的商品价格');
                    }
                    $data['phone'] = isset($_POST['phone']) ? trim($_POST['phone']) : '';
                    if (!preg_match("/^1[34578]{1}\d{9}$/", $data['phone'])) {
                        throw new \Exception('请填写正确的手机号');
                    }
                    $data['order_time'] = isset($_POST['order_time']) ? trim($_POST['order_time']) : '';
                    if (empty($data['order_time'])) {
                        throw new \Exception('请填写您的送餐时间');
                    }
                    $sql = "INSERT INTO `order` (`user_name` ,`goods_name`,`price`,`phone`,`order_time`,`add_time`) VALUES (:user_name, :goods_name, :price, :phone, :order_time, :add_time)";
                    $stmt = $dbh->prepare($sql);
                    $stmt->execute([':user_name' => $data['user_name'], ':goods_name' => $data['goods_name'], ':price' => $data['price'], ':phone' => $data['phone'], ':order_time' => $data['order_time'], ':add_time' => $nowDateTime]);
                    $lastId = $dbh->lastinsertid();
                    if (!$lastId) {
                        throw new \Exception('提交失败');
                    }
                    $data = [];
                    $success = '提交成功';
                } catch (\Exception $e) {
                    $error = $e->getMessage();
                }

                break;
            case 'stoporder'://停止点餐
                $data['admin_password'] = isset($_POST['admin_password']) ? trim($_POST['admin_password']) : '';
                $data['lock_type'] = isset($_POST['lock_type']) ? trim($_POST['lock_type']) : '';
                try {
                    if ($data['admin_password'] != 'duchenggogogo') {
                        throw new \Exception('您输入的管理员口令有误');
                    }
                    if (!in_array($data['lock_type'], ['lock', 'unlock'])) {
                        throw new \Exception('操作类型有误');
                    }
                    if ($data['lock_type'] == 'lock') {
                        $sql = "INSERT INTO `order_lock` (`password` ,`lock_time`,`add_time`) VALUES (:password, :lock_time, :add_time)";
                        $stmt = $dbh->prepare($sql);
                        $stmt->execute([':password' => $data['admin_password'], ':lock_time' => $nowDate, ':add_time' => $nowDateTime]);
                        $lastId = $dbh->lastinsertid();
                        if (!$lastId) {
                            throw new \Exception('锁定失败');
                        }
                        $success = '锁定成功';
                    } elseif ($data['lock_type'] == 'unlock') {
                        $sql = "DELETE FROM `order_lock` WHERE `lock_time` = '" . $nowDate . "'"; //kevin%
                        $stmt = $dbh->prepare($sql);
                        $stmt->execute();
                        $delCount = $stmt->rowCount();
                        if ($delCount > 0) {
                            $success = '解锁成功';
                        } else {
                            $error = '解锁失败';
                        }
                    }
                } catch (\Exception $e) {
                    $error = $e->getMessage();
                }
                $data = [];
                break;
            case 'delorder'://取消订单
                $data['order_id'] = isset($_POST['order_id']) ? (int) $_POST['order_id'] : 0;
                $data['phone'] = isset($_POST['phone']) ? trim($_POST['phone']) :'';
                try {
                    $sql = "SELECT * FROM `order` WHERE `order_id` = :order_id";
                    $stmt = $dbh->prepare($sql);
                    $stmt->execute([':order_id' => $data['order_id']]);
                    $orderRow = $stmt->fetch(PDO::FETCH_ASSOC);
                    if (empty($orderRow)) {
                        throw new \Exception('订单不存在');
                    }
                    if ($orderRow['phone'] != $data['phone']) {
                        throw new \Exception('手机号不正确');
                    }
                    $sql = "UPDATE `order` SET `is_del`=1,mod_time=:mod_time WHERE `order_id`=:order_id";
                    $stmt = $dbh->prepare($sql);
                    $stmt->execute(array(':order_id' => $data['order_id'], ':mod_time' => $nowDateTime));
                    $modCount = $stmt->rowCount();
                    if ($modCount > 0) {
                        $success = '取消成功';
                    } else {
                        throw new \Exception('取消订单失败，请检查你的手机号是否和订单对应');
                    }
                }catch (\Exception $e){
                    $error = $e->getMessage();
                }
                break;
            default:
                $error = '无效提交类型';
        }
    }
    //查询点餐数据
    $sql = "SELECT * FROM `order` WHERE `order_time` >= :now_date AND `is_del`=0 ORDER BY `order_time` ASC";
    $stmt = $dbh->prepare($sql);
    $stmt->execute([':now_date' => $nowDate]);
    $orderList = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $groupOrderList = [];
    if ($orderList) {
        foreach ($orderList as $v) {
            isset($groupOrderList[$v['order_time']]) || $groupOrderList[$v['order_time']] = [];
            $groupOrderList[$v['order_time']][] = $v;
        }
    }
    ?>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3个meta标签*必须*放在最前面，任何其他内容都*必须*跟随其后！ -->
    <title>都城点餐系统</title>

    <!-- Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim 和 Respond.js 是为了让 IE8 支持 HTML5 元素和媒体查询（media queries）功能 -->
    <!-- 警告：通过 file:// 协议（就是直接将 html 页面拖拽到浏览器中）访问页面时 Respond.js 不起作用 -->
    <!--[if lt IE 9]>
    <script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <!-- bootstrap-datetimepicker -->
    <link href="https://cdn.bootcss.com/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css"
          rel="stylesheet">
</head>
<body>
<div class="container">
    <div class="starter-template">
        <h1>都城点餐系统</h1>
        <p class="lead">请尽早完成点餐</p>
        <div>菜单地址：<a class="btn btn-primary" href="http://www.dcyz.com/monthmenu.aspx" target="_blank"> 点击跳转</a></div>
        <hr>
    </div>
    <div class="row">
        <?php if (!empty($error)) { ?>
            <div class="alert alert-danger alert-dismissible" role="alert">
                <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
                <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <?php echo $error; ?>
            </div>
        <?php } ?>
        <?php if (!empty($success)) { ?>
            <div class="alert alert-success alert-dismissible" role="alert">
                <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
                <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <?php echo $success; ?>
            </div>
        <?php } ?>
        <?php if ($isLock) { ?>
            <div class="alert alert-info alert-dismissible" role="alert">
                <strong>系统已经锁定，今天不能点餐了，下次记得及时点餐</strong>
            </div>
        <?php } ?>
        <div class="col-sm-6 border-right">
            <form class="form-horizontal" method="post">
                <input type="hidden" name="type" value="suborder">
                <div class="form-group">
                    <label for="user_name" class="col-sm-4 control-label">姓名：</label>
                    <div class="col-sm-6">
                        <input type="text" class="form-control" id="user_name" name="user_name" placeholder="订餐者姓名"
                               value="<?php echo !empty($data['user_name']) ? $data['user_name'] : ''; ?>">
                    </div>
                </div>
                <div class="form-group">
                    <label for="goods_name" class="col-sm-4 control-label">菜名：</label>
                    <div class="col-sm-6">
                        <input type="text" class="form-control" id="goods_name" name="goods_name" placeholder="请输入菜名"
                               value="<?php echo !empty($data['goods_name']) ? $data['goods_name'] : ''; ?>">
                    </div>
                </div>
                <div class="form-group">
                    <label for="price" class="col-sm-4 control-label">价格：</label>
                    <div class="col-sm-6">
                        <input type="number" min="0" step="1" class="form-control" id="price" name="price"
                               value="<?php echo !empty($data['price']) ? $data['price'] : '17'; ?>" placeholder="">
                    </div>
                </div>
                <div class="form-group">
                    <label for="phone" class="col-sm-4 control-label">送餐日期：</label>
                    <div class="col-sm-6">
                        <div class="input-group date form_datetime">
                            <input type="text" class="form-control" id="order_time" name="order_time"
                                   value="<?php echo !empty($data['order_time']) ? $data['order_time'] : date('Y-m-d') ?>"
                                   placeholder="">
                            <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label for="phone" class="col-sm-4 control-label">手机号：</label>
                    <div class="col-sm-6">
                        <input type="text" class="form-control" id="phone" name="phone"
                               value="<?php echo !empty($data['phone']) ? $data['phone'] : ''; ?>"
                               placeholder="手机号用来取消订单">
                    </div>
                </div>
                <?php if (!$isLock) { ?>
                    <div class="form-group">
                        <button type="submit" class="btn btn-primary col-sm-offset-4">下单</button>
                    </div>
                <?php } ?>
            </form>
        </div>
        <div class="col-sm-6 border border-left">
            <form class="form-inline" method="post">
                <input type="hidden" name="type" value="stoporder">
                <input type="hidden" name="lock_type" value="<?php echo $isLock ? 'unlock' : 'lock' ?>">
                <div class="form-group">
                    <label for="admin_password">管理口令：</label>
                    <input type="password" class="form-control" name="admin_password" id="admin_password"
                           placeholder="密码">
                </div>
                <button type="submit" class="btn btn-success"><?php echo $isLock ? '重启点餐' : '停止点餐'; ?></button>
            </form>
        </div>
    </div>
    <div class="row">
        <?php
        if ($groupOrderList) {
            foreach ($groupOrderList as $date => $orderList) {
                $orderIndex = 1;
                ?>
                <p class="bg-success">送餐日期：<?php echo $date; ?></p>
                <table class="table table-striped">
                    <thead>
                    <tr>
                        <th>#</th>
                        <th>姓名</th>
                        <th>菜名</th>
                        <th>价格</th>
                        <th>送餐日期</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($orderList as $key => $order) { ?>
                        <tr>
                            <th scope="row"><?php echo $orderIndex?></th>
                            <td><?php echo $order['user_name']?></td>
                            <td><?php echo $order['goods_name']?></td>
                            <td>
                                ￥<?php echo $order['price']?>
                                <?php
                                if ($order['price'] > 16){
                                    echo '<span class="label label-info">差价：￥'. ($order['price'] - 16) .'</span>';
                                }
                                ?>
                                </td>
                            <td><?php echo $order['order_time']?></td>
                            <td>
                                <form class="form-inline" method="post">
                                    <input type="hidden" name="order_id" value="<?php echo $order['order_id']?>">
                                    <input type="hidden" name="type" value="delorder">
                                    <input type="text" class="form-control" name="phone" placeholder="下单手机号">
                                    <button type="submit" class="btn btn-danger">取消</button>
                                </form>
                            </td>
                        </tr>
                    <?php
                        $orderIndex ++ ;
                    }
                    ?>
                    </tbody>
                </table>
                <hr>
            <?php }
        } ?>
    </div>
</div><!-- /.container -->
<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery，所以必须放在前边) -->
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- moment -->
<script src="https://cdn.bootcss.com/moment.js/2.21.0/moment.min.js"></script>
<script src="https://cdn.bootcss.com/moment.js/2.21.0/locale/zh-cn.js"></script>
<!-- bootstrap-datetimepicker -->
<script src="https://cdn.bootcss.com/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<script type="application/javascript">
    $(function () {
        $("#order_time,.form_datetime").datetimepicker({
            format: "YYYY-MM-DD"
        });
    });
</script>
<?php if ($error || $success){?>
<script type="text/javascript">
    setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
        window.location.href = 'menu.php';//页面刷新
    },1000);
</script>
<?php }?>
</body>
</html>
